<?php
//微信接口

namespace Weixin\Controller;

use Think\Controller;

class HandleEventController extends Controller{

	public $openid = '';

	public function index(){
		echo 'No Access';
	}

	public function __construct($postObj){
		parent::__construct();

		$this->openid =  $postObj->FromUserName;

		switch ($postObj->Event) {
			case 'CLICK':
				$this->handleClick($postObj);	//自定义菜单事件
				break;
			case 'LOCATION':
				$this->handleEventLocation($postObj);	//上报地理位置事件
				break;
			case 'subscribe':
				$this->handleSubscribe($postObj);	//订阅事件
				break;
			case 'unsubscribe':
				$this->handleUnsubscribe($postObj);	//取消订阅事件
				break;
			default:
				# code...
				break;
		}
	}
/**
 * 订阅事件
 * @param  [type] $postObj [description]
 * @return [type]          [description]
 */
	public function handleSubscribe($postObj){
		// 
        $is_service = D('WeixinConfig')->getService();
        /**
         * 根据openid 获取 user_id
         * 不为空说明存在该用户
         */
        $where = "openid='".$this->openid."'";

        $user_id = M('weixin_user')->where($where)->getField('id');

        if($user_id){					
        	// 已经存在该用户
        	// 更新信息
        	if( $is_service ){
    			$user_info = get_user_info( $this->openid , get_access_token() );
    			M('weixin_user')->save($user_info);

        	} else {
	        	$data['isSub'] = 1;
	        	$data['updatetime'] = time();
	        	M('weixin_user')->where('id='.$user_id)->save($data);

        	}

        }else{							
        	// 不存在
        	// 
        	if( $is_service ){
    			$user_info = get_user_info($openid,get_access_token());
    			$res = M('weixin_user')->add($user_info);
        	} else {
        		$data['openid'] 		= $this->openid.'';
        		$data['subscribe_time'] = time();
	        	$data['isSub']  		= 1;
	        	$data['updatetime'] 	= time();
	        	M('weixin_user')->add($data);
        	}

        }

		$newArr = array(
			array(
				'title' => '欢迎关注湖八鲜',
				'description' => '开始兑券',
				'picurl' => 'http://single.wzxing.com/1.jpg',
				'url' => 'http://single.wzxing.com/weixin/index/index/openid/'.$this->openid,
			),
		);

		returnNews($postObj,$newArr);
	}

/**
 * 取消订阅事件
 * @param  [type] $postObj [description]
 * @return [type]          [description]
 */
	public function handleUnsubscribe($postObj){
		M('weixin_user')->where("openid='".$this->openid."'")->setField('isSub',0);
	}

/**
 * 上报地理位置事件
 * 请选择获取地理位置的模式
 * 用户进行对话时上报一次
 * 用户进行对话后每隔5s上报一次
 * @param  [type] $postObj [description]
 * @return [type]          [description]
 */
	public function handleEventLocation($postObj){
// ToUserName	开发者微信号
// FromUserName	 发送方帐号（一个OpenID）
// CreateTime	 消息创建时间 （整型）
// MsgType	 消息类型，event
// Event	 事件类型，LOCATION
// Latitude	 地理位置纬度
// Longitude	 地理位置经度
// Precision	 地理位置精度
		$data['longitude'] = $postObj->Longitude.'';
		$data['latitude']  = $postObj->Latitude.'';
		
		$res = M('weixin_user')->where("openid='".$this->openid."'")->save($data);
	}


/**
 * 自定义菜单事件
 * @param  [type] $postObj [description]
 * @return [type]          [description]
 */
	public function handleClick($postObj){
		//事件KEY值，与自定义菜单接口中KEY值对应
		$EventKey = $postObj->EventKey;

		// $this->$EventKey($postObj);
		switch ($EventKey) {
			case 'exchange':
				$this->exchange($postObj);
				break;
			case 'find':
				$this->find($postObj);
				break;
			
			default:
				# code...
				break;
		}

		// returnText($postObj,$EventKey);
		// if($EventKey)
        
	}


	/**
	 * 我要兑换
	 * @return [type] [description]
	 */
	public function exchange($postObj){

		$newArr = array(
			array(
				'title' => '开始兑券',
				'description' => '开始兑券',
				'picurl' => 'http://single.wzxing.com/1.jpg',
				'url' => 'http://single.wzxing.com/weixin/index/index/openid/'.$this->openid,
			),
		);
		returnNews($postObj,$newArr);
	}

	/**
	 * 我要查询
	 * @return [type] [description]
	 */
	public function find($postObj){

		$map['openid'] = "$this->openid";

		$orders = D('Order')->relation(true)->where($map)->order('create_time desc')->limit(8)->select();
		// returnText($postObj,serialize($orders));
		// 
		$newArr = array(
			array(
				'title' => '以下为兑换列表',
				'description' => '',
				'picurl' => 'http://single.wzxing.com/1.jpg',
				'url' => 'http://single.wzxing.com/weixin/index/index/openid/'.$this->openid,
			),
		);

		foreach ($orders as $key => $value) {
			if(empty($value['name']) || empty($value['phone']) || empty($value['sheng']) || empty($value['shi']) || empty($value['qu']) || empty($value['address']) ){
				// 信息不完整
				$img = 'xxbq.png';
			}else{
				if($value['status'] == 1){
					if($value['order_number']){
						$img = 'yfh.png';
					}else{
						$img = 'dfh.png';
					}
				}else{
					$img = 'dqr.png';
				}

			}

			$newArr[] = array(
				'title' => '类型'.$value['card']['type'].' 卡号'.$value['card']['card'],
				'description' => '查看详情',
				'picurl' => 'http://single.wzxing.com/Public/images/'.$img,
				'url' => 'http://single.wzxing.com/weixin/order/write/openid/'.$this->openid.'/id/'.$value['id'],
			);
		}

		// if(count($orders) == 8){
			$newArr[] = array(
				'title' => '查看全部',
				'description' => '查看更多',
				'picurl' => 'http://single.wzxing.com/all.png',
				'url' => 'http://single.wzxing.com/weixin/order/index/openid/'.$this->openid,
			);
		// }

		returnNews($postObj,$newArr);

	}







}
